var router = require('koa-router')({
    prefix: '/project/:id'
});
var models = require('./../../../models');
var q = require('q');


router.get('/mileconfig', function* (next) {
    var device = yield models.DistDeviceConfig.findOne({
        where: {
            prjId: this.params.id
        }
    });
    var mileSums = yield models.sequelize.query('select sum(Value) as mileSum from DistMileResult where DeviceId = ' + device.deviceId + ' and ConfigId = ' + device.id, { type: models.sequelize.QueryTypes.SELECT });
    var mileSum = mileSums[0].mileSum || 0;
    this.render('project/mile.config.jade', {
        project: this.state.project,
        mileSum: mileSum.toFixed(3),
        url: this.request.url
    });
});

router.post('/mileconfig', function* (next) {
    var device = yield models.DistDeviceConfig.findOne({
        where: {
            prjId: this.params.id
        }
    });
    if (this.request.body.mile) {
        var newSum = parseFloat(this.request.body.mile);
        yield models.DistMileResult.create({
            configId: device.id,
            deviceId: device.deviceId,
            value: newSum,
            date: new Date()
        });
    }
    this.redirect(`/project/${this.params.id}/mileconfig`);
});

module.exports = router.routes();
